package com.mazegame.backend;

import javax.swing.JPanel;

import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.application.Platform;
import java.awt.BorderLayout;

public class BackgroundPanel extends JPanel {
    private JFXPanel jfxPanel;
    private String imagePath;

    public BackgroundPanel(String imagePath) {
        this.imagePath = imagePath;
        //this.imagePath = "/img/bk.png";
        setLayout(new BorderLayout());
        // 初始化 JFXPanel
        jfxPanel = new JFXPanel();
        add(jfxPanel, BorderLayout.CENTER);
        // 在 JavaFX 线程中初始化场景
        Platform.runLater(this::initFX);
    }

    public BackgroundPanel(String imagePath,int sign) {
        this.imagePath = imagePath;
        //this.imagePath = "/img/bk.png";
        setLayout(new BorderLayout());
        // 初始化 JFXPanel
        jfxPanel = new JFXPanel();
        add(jfxPanel, BorderLayout.CENTER);
        // 在 JavaFX 线程中初始化场景
        Platform.runLater(this::initFX2);
    }
    private void initFX2() {
        try {
            // 从类路径加载图片资源
            String resourcePath = BackgroundPanel.class.getResource(imagePath).toExternalForm();
            Image image = new Image(resourcePath);
            // 创建场景并添加图片
            StackPane root = new StackPane();
            Scene scene = new Scene(root);
            ImageView imageView = new ImageView(image);
            imageView.setPreserveRatio(true);// 锁定宽高比
            //imageView.fitWidthProperty().bind(scene.widthProperty());
            //imageView.fitHeightProperty().bind(scene.heightProperty());
            root.getChildren().add(imageView);
            jfxPanel.setScene(scene);
        } catch (Exception e) {
            System.err.println("无法加载背景图片: " + e.getMessage());
            // 可以添加默认背景或错误处理
        }
    }

    private void initFX() {
        try {
            // 从类路径加载图片资源
            String resourcePath = BackgroundPanel.class.getResource(imagePath).toExternalForm();
            Image image = new Image(resourcePath);
            // 创建场景并添加图片
            StackPane root = new StackPane();
            Scene scene = new Scene(root);
            ImageView imageView = new ImageView(image);
            imageView.setPreserveRatio(true);
            imageView.fitWidthProperty().bind(scene.widthProperty());
            imageView.fitHeightProperty().bind(scene.heightProperty());
            // 不锁定宽高比
            imageView.setPreserveRatio(false);
            root.getChildren().add(imageView);
            jfxPanel.setScene(scene);
        } catch (Exception e) {
            System.err.println("无法加载背景图片: " + e.getMessage());
            // 可以添加默认背景或错误处理
        }
    }
}